//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package api_coll_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// 迁移数据使用
type ApiCollInfoDbItem struct {
	ApiCollId            string   `bson:"_id"`
	ProjectId            string   `bson:"projectId"`
	Name                 string   `bson:"name"`
	DefaultAddr          string   `bson:"defaultAddr"`
	ApiCollType          uint32   `bson:"apiCollType"`
	CreateTime           int64    `bson:"createTime"`
	CreateUserId         string   `bson:"createUserId"`
	UpdateTime           int64    `bson:"updateTime"`
	UpdateUserId         string   `bson:"updateUserId"`
	EditMemberUserIdList []string `bson:"editMemberUserIdList"`
}

type _InfoDao struct {
	mc *mongo.Collection
}

func newInfoDao(db *mongo.Database) (*_InfoDao, error) {
	mc := db.Collection(db_ns.DB_NS_API_COLLECTION + "info")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"projectId", 1}, {"updateTime", -1}},
	})
	if err != nil {
		return nil, err
	}
	return &_InfoDao{mc: mc}, nil
}

func (db *_InfoDao) List(ctx context.Context, projectId string, filterByWatch bool, watchApiCollIdList []string, offset, limit int64) ([]*ApiCollInfoDbItem, error) {
	query := bson.M{"projectId": projectId}
	if filterByWatch {
		query["_id"] = bson.M{"$in": watchApiCollIdList}
	}
	cursor, err := db.mc.Find(ctx, query, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"updateTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*ApiCollInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_InfoDao) ListAllForUpgrade(ctx context.Context) ([]*ApiCollInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{})
	if err != nil {
		return nil, err
	}
	retList := []*ApiCollInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
